package com.tronsis.distribution.activity.me.points;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.PopupWindow;

import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.tronsis.distribution.R;
import com.tronsis.distribution.bean.UploadFileBean;
import com.tronsis.distribution.biz.factory.FileBizFactory;
import com.tronsis.distribution.biz.factory.UserBizFactory;
import com.tronsis.distribution.http.Url;
import com.tronsis.distribution.util.GlideImageLoader;
import com.tronsis.library.activity.ToolBarBaseActivity;
import com.tronsis.library.http.UICallBack;
import com.tronsis.library.imageloader.ImageLoader;
import com.tronsis.library.util.LogUtil;
import com.tronsis.library.util.StringUtil;
import com.tronsis.library.util.ToastUtil;
import com.tronsis.library.util.WindowUtil;

import java.io.File;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class PointGrievanceActivity extends ToolBarBaseActivity {

    @BindView(R.id.iv_report_image)
    ImageView mIvReportImage;
    @BindView(R.id.iv_plus)
    ImageView mIvPlus;
    @BindView(R.id.fl_report_image)
    FrameLayout mFlReportImage;
    @BindView(R.id.btn_submit)
    Button mBtnSubmit;

    private static final int REQ_CAMERA = 124;
    private static final int REQUEST_CAMERA = 125;
    private static final int REQUEST_ALBUM = 126;
    @BindView(R.id.et_reason)
    EditText mEtReason;
    @BindView(R.id.et_description)
    EditText mEtDescription;
    private PopupWindow mPopupWindow;

    private String mImageFid;

    private String mWithdrawId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_point_grievance);
        ButterKnife.bind(this);
        setTitle(true, getString(R.string.grievance));
        mWithdrawId = getIntent().getStringExtra("withdrawId");
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS && data != null) {
            List<ImageItem> imageItems = (List<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
            if (imageItems != null && imageItems.size() > 0) {
                ImageLoader.display(mContext, imageItems.get(0).path, mIvReportImage);
                mIvPlus.setVisibility(View.GONE);
                httpUploadAvatar(new File(imageItems.get(0).path));
            }
        }


    }

    @OnClick(R.id.fl_report_image)
    void reportImageClick() {
        showPopupWindow();
    }

    @OnClick(R.id.btn_submit)
    void submitClick() {
        String reason = mEtReason.getText().toString();
        String detail = mEtDescription.getText().toString();
        if(StringUtil.isBlank(reason)){
            ToastUtil.showMessage(this,"请输入申请原因");
            return;
        }

        if(StringUtil.isBlank(detail)){
            ToastUtil.showMessage(this,"请输入具体描述");
            return;
        }

        httpPointReport(mWithdrawId,mImageFid,reason,detail);
    }

    private void showPopupWindow() {
        View view = LayoutInflater.from(mContext).inflate(R.layout.dialog_album_camera, null);
        // 强制隐藏键盘
        InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
        if (mPopupWindow == null) {

            ImagePicker imagePicker = ImagePicker.getInstance();
            imagePicker.setImageLoader(new GlideImageLoader());
            imagePicker.setCrop(false);
            imagePicker.setMultiMode(false);
            imagePicker.setShowCamera(true);

            mPopupWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            mPopupWindow.setFocusable(true);
            mPopupWindow.setOutsideTouchable(true);
            /* mPopupWindow.setBackgroundDrawable(new BitmapDrawable());*/
            mPopupWindow.setAnimationStyle(R.style.AnimationBottomDialog);
            mPopupWindow.setTouchInterceptor(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View view, MotionEvent motionEvent) {
                    if (motionEvent.getAction() == MotionEvent.ACTION_OUTSIDE) {
                        mPopupWindow.dismiss();
                        return true;
                    }
                    return false;
                }
            });
            mPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    WindowUtil.setPopWindowBackgroundAlpha(PointGrievanceActivity.this, 1f);
                }
            });
            view.findViewById(R.id.btn_cancel).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    mPopupWindow.dismiss();
                }
            });
            view.findViewById(R.id.btn_camera).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    mPopupWindow.dismiss();
                    checkPermission(new CheckPermListener() {
                        @Override
                        public void superPermission() {
                            Intent intent = new Intent(mContext, ImageGridActivity.class);
                            intent.putExtra(ImageGridActivity.EXTRAS_TAKE_PICKERS, true);
                            startActivityForResult(intent, REQUEST_CAMERA);
                            mPopupWindow.dismiss();
                        }
                    }, R.string.ask_again, Manifest.permission.CAMERA);
                }
            });
            view.findViewById(R.id.btn_album).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    mPopupWindow.dismiss();
                    checkPermission(new CheckPermListener() {
                        @Override
                        public void superPermission() {
                            Intent intent = new Intent(mContext, ImageGridActivity.class);
                            intent.putExtra(ImageGridActivity.EXTRAS_TAKE_PICKERS, false);

                            startActivityForResult(intent, REQUEST_ALBUM);
                            mPopupWindow.dismiss();
                        }
                    }, R.string.ask_again, Manifest.permission.READ_EXTERNAL_STORAGE);
                }
            });
        }
        WindowUtil.setPopWindowBackgroundAlpha(PointGrievanceActivity.this, 0.7f);
        mPopupWindow.showAtLocation(view, Gravity.BOTTOM, 0, 0);
    }

    private void httpUploadAvatar(final File file) {
        try {
            FileBizFactory.createBiz().upload(this, file, Url.FILE_TYPE_IMAGE, new UICallBack() {
                @Override
                public void onStart() {
                    showLoadingDialog();
                }

                @Override
                public void onRefresh(Object data) {
                    UploadFileBean fileBean = (UploadFileBean) data;
                    LogUtil.e("file", fileBean.getId());
                    mImageFid = fileBean.getId();
                    dismissLoadingDialog();
                }

                @Override
                public void onFailure(int status) {
                    dismissLoadingDialog();
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void httpPointReport(String withdrawId, String imageFid, String detail, String reason) {
        try {
            UserBizFactory.createBiz().reportPointWithDraw(this, withdrawId, detail, imageFid, reason, new UICallBack() {
                @Override
                public void onStart() {
                    showLoadingDialog();
                }

                @Override
                public void onRefresh(Object data) {
                    dismissLoadingDialog();
                    setResult(RESULT_OK);
                    finish();
                }

                @Override
                public void onFailure(int status) {
                    dismissLoadingDialog();
                }
            });
        } catch (Exception e) {
            dismissLoadingDialog();
            e.printStackTrace();
        }
    }
}
